// shop/pages/shoppingcart/index.js
import api from '../../../utils/api'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        shopCartItems: [],
        // picDomain: config.picDomain,
        isManage: false, // 管理
        shopCartItemDiscounts: [],
        finalMoney: 0,
        totalMoney: 0,
        subtractMoney: 0,
        allChecked: false
    },
    /**
     * 删除 
     */
    onDel(e) {
      const _this = this
      const value = e.currentTarget.dataset.id
      wx.showModal({
        title: '',
        content: '确认要删除该商品吗？',
        confirmColor: "#eb2444",
        success(res) {
          if (res.confirm) {
            wx.showLoading({
                mask: true
            });
            api.post(`/api/hxhealth/shopcart/remove`, {
                data: {value: value}
            }).then(res => {
							let pages=getCurrentPages();  //获取当前页面
							let beforePage=pages[pages.length-2]  //获取上一个页面的实例
							if(beforePage.getShopCarNum) {
								beforePage.getShopCarNum()
							}
                wx.showToast({
                    title: '删除成功',
                    complete: () => {
                      _this.loadBasketData()
                    }
                })
                
            }).catch(e => {
                wx.showToast({
                    icon: 'none',
                    title: '删除失败：' + e,
                })
            })
          }
        }
      })
    },
    share() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(e) {
      const _this = this
      const idx = e.currentTarget.dataset.index
      const title = e.currentTarget.dataset.title
      const kindid = e.currentTarget.dataset.kindid
      const id = e.currentTarget.dataset.id
      const imageUrl = e.currentTarget.dataset.image
      return {
        title: title || '分享标题', // 分享标题
        path: `/redStarNews/pages/desic/index?idx=${idx}&desic=enterprise&kindid=${id}`, // 分享时打开的页面路径
        imageUrl: imageUrl || '', //（可选）分享的图片 URL
        success: function (shareTickets) {
          console.log('分享成功', shareTickets);
          _this.forward(id)
        },
        fail: function (err) {
          console.log('分享失败', err);
        }
      }
    },
    /**
     * 转发登记
     * @param {} id 
     */
    forward(id) {
      api.get(`/api/hxhealth/article/forward/${id}`).then(res => {
        this.reloadList()
      }).catch(error => {
        wx.showToast({
          title: error.faultstring,
          icon: 'none',
          duration: 3000
        })
      })
    },
    /**
     * 收藏操作
     * @param {*} e 
     */
    async optionCollect(e) {
      const id = e.currentTarget.dataset.id
      const collect = e.currentTarget.dataset.collect
      if(collect==1) {
        if(await this.onUncollect(id)) {
          this.loadBasketData()
        }
      } else {
        if(await this.onCollect(id)) {
          this.loadBasketData()
        }
      }
    },
    /**
     * 收藏
     * @param {} id 
     */
    onCollect(id) {
      return new Promise((resolve) => {
        api.get(`/api/hxhealth/article/collect/${id}`).then(res => {
          wx.showToast({
            title: '收藏成功',
            icon: 'none',
            duration: 2000,
            complete:(res) => {
              resolve(true)
            }
          })
        }).catch(error => {
          wx.showToast({
            title: error.faultstring,
            icon: 'none',
            duration: 3000,
            complete:(res) => {
              resolve(false)
            }
          })
        })
      })
    },
    /**
     * 取消收藏
     * @param {} id   
     */
    onUncollect(id) {
      return new Promise((resolve) => {
        api.get(`/api/hxhealth/article/uncollect/${id}`).then(res => {
          wx.showToast({
            title: '取消收藏',
            icon: 'none',
            duration: 1000,
            complete:(res) => {
              resolve(true)
            }
          })
        }).catch(error => {
          wx.showToast({
            title: error.faultstring,
            icon: 'none',
            duration: 3000,
            complete:(res) => {
              resolve(false)
            }
          })
        })
      })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.setNavigationBarTitle({ title: '购物车'})
        this.loadBasketData()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.loadBasketData();
        //   http.getCartCount();//重新计算购物车总数量
    },
    //开始管理
    optManage() {
        this.setData({
            isManage: !this.data.isManage
        })
    },
    getImgUrl(element) {
        var images = element.goodsimages;
        // 判断是否为数组转换的字符串
        let resultUrl = ''
        if (images.startsWith('[')) {
            // 是数组转换的字符串，进行处理
            // console.log('第一种情况：数组转换的字符串', i, images);
            var imagesArray = JSON.parse(images);
            resultUrl = imagesArray?.[0]?.file || '';
            // console.log("第一种情况：数组转换的字符串");
        } else {
            // console.log('第二种情况：逗号隔开的图片地址');
            // 是逗号隔开的图片地址，进行处理
            var imageUrls = images.split(',');
            resultUrl = imageUrls?.[0] || '';
        }
        return resultUrl
    },
    // 加载购物车数据
    loadBasketData() {
        const _this = this
        // wx.showLoading(); //加载购物车
        try {
            api.post('/api/hxhealth/shopcart/list').then((res) => {
                // console.log(res);
                console.log('----res shopCartItems----', res);
                if (res.length > 0) {
                    // 默认不选中
                    const shopCartItems = res || [];
                    shopCartItems.forEach(shopCartItem => {
                        shopCartItem.prodName = shopCartItem?.goodsid?.[1] || '';
                        shopCartItem.id = shopCartItem?.id || '';
                        shopCartItem.goodsimages = _this.getImgUrl(shopCartItem);
                        shopCartItem.checked = false;
                    });

                    this.setData({
                        shopCartItems: shopCartItems || [],
                        allChecked: false
                    });
                } else {
                    this.setData({
                        shopCartItems: []
                    });
                }
                this.calTotalPrice(); //计算总价
                // wx.hideLoading();
            });
        } catch (e) {
            console.error(e);
        }
    },

    /**
     * 去结算
     */
    toFirmOrder: function () {
        //   var shopCartItemDiscounts = this.data.shopCartItemDiscounts;
        var basketIds = [];
        //   shopCartItemDiscounts.forEach(shopCartItemDiscount => {
        shopCartItems.forEach(shopCartItem => {
            if (shopCartItem.checked) {
                basketIds.push(shopCartItem.basketId)
            }
        })
        //   })
        if (!basketIds.length) {
            wx.showToast({
                title: '请选择商品',
                icon: "none"
            })
            return
        }
        wx.setStorageSync("basketIds", JSON.stringify(basketIds));
        wx.navigateTo({
            url: '/pages/submit-order/submit-order?orderEntry=0',
        })
    },
    onSubmit() {
        if(!this.data.isManage) {
            const list = this.data.shopCartItems || []
            const prodNames = list.filter(v => v.checked)?.map(v => v.prodName)?.join(',')
            console.log(prodNames,'prodNames')
            if(!prodNames) {
                wx.showToast({
                    title: '请选择要结算的商品',
                    icon: "none"
                })
                return
            }
            wx.navigateTo({
                url: `/shop/pages/submitorder/index?prodNames=${prodNames}`,
            })
        } else {
            this.onDelBasket()
        }
    },
    /**
     * 全选
     */
    onSelAll: function () {
        var allChecked = this.data.allChecked;
        allChecked = !allChecked; //改变状态
        var cItems = this.data.shopCartItems;
        for (var j = 0; j < cItems.length; j++) {
            cItems[j].checked = allChecked;
        }
        this.setData({
            allChecked: allChecked,
            shopCartItems: cItems
        });
        this.calTotalPrice(); //计算总价
    },

    /**
     * 每一项的选择事件
     */
    onSelectedItem: function (e) {
        var index = e.currentTarget.dataset.index;
        var shopCartItems = this.data.shopCartItems; // 获取购物车列表
        shopCartItems[index].checked = e.detail; // 改变状态
        this.setData({
            shopCartItems: shopCartItems
        });
        this.checkAllSelected(); //检查全选状态
        this.calTotalPrice(); //计算总价
    },

    /**
     * 检查全选状态
     */
    checkAllSelected: function () {

        var flag = false;
        var cItems = this.data.shopCartItems;
        for (var j = 0; j < cItems.length; j++) {
            if (!cItems[j].checked) {
                flag = true;
                break;
            }
        }
        this.setData({
            allChecked: !flag
        });
    },

    /**
     * 计算购物车总额
     */
    calTotalPrice: function () {
        var cItems = this.data.shopCartItems;
        let total = 0
        for (var j = 0; j < cItems.length; j++) {
            if (cItems[j].checked) {
                total += (parseFloat(cItems[j].goodsprice)) * 100 * parseFloat(cItems[j].goodsamount)
            }
        }
        this.categoryPrice();
        this.setData({
            totalMoney: total
        });
    },

    /**
     * 减少数量
     */
    onCountMinus: function (e) {
        const _this = this
        var index = e.currentTarget.dataset.index;
        var shopCartItems = this.data.shopCartItems;
        const amount = parseInt(shopCartItems[index].goodsamount)
        const id = shopCartItems[index]?.goodsid?.[0]
        
        if (amount > 1 && id) {
            wx.showLoading({ mask: true });
            api.post(`/api/hxhealth/shopcart/save`, {
                data: {"goodsamount":-1,"goodsid": id}
            }).then(res => {
                wx.hideLoading();
                _this.updateCount(shopCartItems, index, -1);
            }).catch(e => {
                wx.hideLoading();
                wx.showToast({
                    icon: 'none',
                    title: '操作失败：' + e,
                })
            })
        }
    },

    /**
     * 增加数量
     */
    onCountPlus: function (e) {
        const _this = this
        var index = e.currentTarget.dataset.index;
        var shopCartItems = this.data.shopCartItems;
        const id = shopCartItems[index]?.goodsid?.[0]
        if(!id) { return }
        wx.showLoading({ mask: true });
        api.post(`/api/hxhealth/shopcart/save`, {
            data: {"goodsamount":1,"goodsid": id}
        }).then(res => {
            wx.hideLoading();
            _this.updateCount(shopCartItems, index, 1);
        }).catch(e => {
            wx.hideLoading();
            wx.showToast({
                icon: 'none',
                title: '添加失败：' + e,
            })
        })
    },


    /**
     * 改变购物车数量接口
     */
    updateCount: function (shopCartItems, index, prodCount) {
        var ths = this;
        const amount = shopCartItems[index].goodsamount
        shopCartItems[index].goodsamount = parseInt(amount) + prodCount
        ths.setData({
            shopCartItems: shopCartItems
        });
        ths.calTotalPrice(); //计算总价
    },
    categoryPrice() {
        const shopCartItems = this.data.shopCartItems || []
        shopCartItems.forEach((item) => {
            item.catePrice = (parseInt(item.goodsamount) * parseFloat(item.goodsprice)).toFixed(2)
        })
        this.setData({
            shopCartItems
        })
    },
    /**
     * 删除购物车商品
     */
    onDelBasket: function () {
        const _this = this
        var shopCartItems = this.data.shopCartItems;
        var ids = [];
        for (var j = 0; j < shopCartItems.length; j++) {
            if (shopCartItems[j].checked) {
                ids.push(shopCartItems[j].id);
            }
        }

        if (ids.length == 0) {
            wx.showToast({
                title: '请选择商品',
                icon: "none"
            })
        } else {
            wx.showModal({
                title: '',
                content: '确认要删除选中的商品吗？',
                confirmColor: "#eb2444",
                success(res) {
                    if (res.confirm) {
                        wx.showLoading({
                            mask: true
                        });
                        api.post(`/api/hxhealth/shopcart/remove`, {
                            data: {value: ids.join(',')}
                        }).then(res => {
                            wx.showToast({
                                title: '删除成功',
                                complete: () => {
                                    _this.loadBasketData()
                                }
                            })
                            
                        }).catch(e => {
                            wx.showToast({
                                icon: 'none',
                                title: '删除失败：' + e,
                            })
                        })
                    }
                }
            })
        }


    }


})